<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\PictureLiveUploadsFileController;
use App\Http\Controllers\ZipFileDownloadController;
use App\Models\PictureLive;
use App\Models\PictureLiveBlackUser;
use App\Models\PictureLiveWorks;
use App\Models\UserInfo;
use App\Validate\PictureLiveWorksValidate;
use Illuminate\Support\Facades\DB;

/**
 * 直播活动作品管理
 */
class PictureLiveWorksController extends CommonController
{

    public $model = null;
    public $pictureLiveModel = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new PictureLiveWorks();
        $this->pictureLiveModel = new PictureLive();
        $this->validate = new PictureLiveWorksValidate();
    }

    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param act_id int 活动id
     * @param status int 是否审核 状态  1.已通过   2.未通过   3.未审核(默认)   不传为全部
     * @param keywords string 搜索关键词(作品名称|姓名|编号)
     * @param start_time datetime 投稿时间(开始)
     * @param end_time datetime 投稿时间(截止)
     * @param sort 字段排序  1 默认  2 浏览量  3 点赞 
     */
    public function lists()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('production_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $act_id = $this->request->act_id;
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $status = $this->request->status;
        $sort = $this->request->input('sort', '1');

        $status = empty($status) ? [1, 2, 3] : [$status];
        $res = $this->model->lists(null, $act_id, null, $keywords,  $status, $start_time, $end_time, 2, $sort, 2, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
            if ($val['user_id']) {
                $wechat_info = UserInfo::getWechatField($val['user_id'], ['head_img', 'nickname']);
                $res['data'][$key]['head_img'] = $wechat_info['head_img'];
                $res['data'][$key]['nickname'] = $wechat_info['nickname'];
            } else {
                $res['data'][$key]['head_img'] = $this->getImgAddrUrl() . 'default/default_head_img.png';
                $res['data'][$key]['nickname'] = null;
            }
            $res['data'][$key]['size'] = format_bytes($val['size']); //格式化字节数
        }

        $res = $this->disPageData($res);

        //获取总投票量
        $res['total_vote_num'] = $this->model->getTotalVoteNumber($act_id);

        return $this->returnApi(200, "查询成功", "YES", $res);
    }

    /**
     * 详情
     * @param id int 作品id
     * 
     * //@param status int 是否审核 状态  1.已通过   2.未通过   3.未审核(默认)   不传为全部
     * @param keywords string 搜索关键词(作品名称|姓名|编号)
     * @param start_time datetime 投稿时间(开始)
     * @param end_time datetime 投稿时间(截止)
     * @param sort int 排序方式  1 时间排序（默认）  2 投票排序
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('production_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //用于获取下一个作品
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $sort = $this->request->input('sort', '1');
        $sort = $sort == 2 ? 'vote_num DESC,id ASC' : 'id ASC'; //vote_num ASC,id ASC 解决点赞量全为0时，数据错乱问题

        $res = $this->model
            ->detail($this->request->id, null, [
                'id',
                'act_id',
                'user_id',
                'serial_number',
                'title',
                'cover',
                'img',
                'thumb_img',
                'size',
                'ratio',
                'intro',
                'way',
                'browse_num',
                'vote_num',
                'status',
                'reason',
                'create_time',
                'change_time'
            ]);
        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }
        if ($res['user_id']) {
            $user_info = UserInfo::getWechatField($res['user_id'], ['head_img', 'nickname']);
            $res['head_img'] = $user_info['head_img'] ?? '';
            $res['nickname'] = $user_info['nickname'] ?? '';
        } else {
            $res['head_img'] = $this->getImgAddrUrl() . 'default/default_head_img.png';
            $res['nickname'] = null;
        }

        //获取下一个未审核的活动
        $res->next_data = $this->model->getNextUnchecked($this->request->id, $res->act_id, $keywords, $start_time, $end_time, $sort);

        return $this->returnApi(200, "获取成功", true, $res->toArray());
    }

    /**
     * 审核作品
     * @param id int 作品id
     * @param status int 状态  1.通过  2.未通过   6.已违规
     * @param reason string 拒绝原因、违规原因
     * @param is_black string 图片违规，是否加入黑名单  1 是  2 否
     */
    public function worksCheck()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('works_check')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $id = $this->request->id;
        $status = $this->request->status;
        $is_black = $this->request->is_black ?: 2;
        $reason = $this->request->reason ? $this->request->reason : null;

        if (($status == 2 || $status == 6) && !$reason) {
            return $this->returnApi(202, '请填写拒绝原因');
        }

        $works = $this->model->detail($id, null);
        if (!$works) {
            return $this->returnApi(202, '参数传递错误');
        }
        $works->status = $status;
        $works->reason = $reason;

        DB::beginTransaction();
        try {
            /*消息推送*/
            // if ($works->status == 1) {
            //     $system_id = $this->systemAdd('线上活动：您投稿的作品' . $check_msg, $works->user_id, $works->account_id, 18, intval($works->id), '作品：【' . $works->title . '】' . $check_msg);
            // } else {
            //     $system_id = $this->systemAdd('线上活动：您投稿的作品' . $check_msg, $works->user_id, $works->account_id, 18, intval($works->id), '作品：【' . $works->title . '】' . $check_msg . '，拒绝理由为：' . $this->request->reason);
            // }

            $works->save();
            //加入黑名单
            if ($is_black == 1 && $works->user_id) {
                $pictureLiveBlackUserModel = new PictureLiveBlackUser();
                $data = [
                    'user_id' => $works->user_id,
                ];
                $pictureLiveBlackUserModel->add($data);
            }

            DB::commit();
            return $this->returnApi(200, "审核成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 图片直播，上传图片(单个图片上传)
     * @param user_id 用户id  可选
     * @param act_id int 活动id
     * @param picture_live file 上传文件 名   图片资源（无需预上传）
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('works_add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $pictureLiveModel = new PictureLive();
        $act_info = $pictureLiveModel->detail($this->request->act_id, null, ['con_start_time', 'con_end_time', 'uploads_number', 'uploads_way', 'is_appoint', 'is_check']);
        if (empty($act_info)) {
            return $this->returnApi(201, "活动不存在");
        }
        $act_info = $act_info->toArray();
        //提前一个小时上传
        if ($act_info['con_start_time'] > date('Y-m-d H:i:s', strtotime("+1 hour"))) {
            return $this->returnApi(201, "活动未开始，暂不允许上传");
        }
        //推迟一个小时结束上传
        if ($act_info['con_end_time'] < date('Y-m-d H:i:s', strtotime("-1 hour"))) {
            return $this->returnApi(201, "活动已结束，不允许上传");
        }
        //判断是否可以上传
        if ($act_info['uploads_way'] == 3) {
            return $this->returnApi(201, '此活动，仅支持前台上传，后台不允许上传');
        }

        //计算上传数量
        $pictureLiveWorksModel = new PictureLiveWorks();
        $total_number = $pictureLiveWorksModel->getUserWorksNumber($this->request->act_id);
        $suplus_uploads_number = 500 - $total_number; //总数不能超过500
        if ($suplus_uploads_number <= 0) {
            return $this->returnApi(201, '上传张数已达上限'); //已到达上传限制
        }

        $pictureLiveUploadsFileObj = new PictureLiveUploadsFileController();
        $file_info = $pictureLiveUploadsFileObj->commonUpload($this->request);
        if ($file_info['code'] != 200) {
            return $this->returnApi(201, $file_info['msg']);
        }
        $user_id = $this->request->user_id;
        $data['serial_number'] = $this->model->getSerialNumber('P');
        $data['user_id'] = $user_id;
        $data['act_id'] = $this->request->act_id;
        $data['cover'] = $file_info['content']['cover'];
        $data['img'] = $file_info['content']['img'];
        $data['thumb_img'] = $file_info['content']['thumb_img'];
        $data['width'] = $file_info['content']['width'];
        $data['height'] = $file_info['content']['height'];
        $data['size'] = $file_info['content']['size'];
        $data['ratio'] = $file_info['content']['ratio'];
        $data['way'] = 2;
        $data['status'] = $act_info['is_check'] == 2 ? 1 : 3;
        DB::beginTransaction();
        try {
            $this->model->add($data);

            /*消息推送*/
            // $system_id = $this->systemAdd('线上大赛投稿作品', $user_id, $account_id, 3, intval($this->model->id), '线上大赛：【' . $contestInfo->title . '】投稿成功，等待后台管理员审核！');

            $msg = $act_info['is_check'] == 2 ? '上传成功!' : '上传成功，等待后台管理员审核!';

            DB::commit();
            return $this->returnApi(200, $msg, true); //返回用户已投稿数量
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 图片直播，上传图片(批量上传)
     * @param user_id 用户id  可选
     * @param act_id int 活动id
     * @param content string json 格式   [{"img":"picture_live\/2023-05-17\/zsCwGEDXx2OyVuWpJx6EqSCZTwNEkqUyErUtxYYP.png","width":260,"height":260,"ratio":"260x260","size":7735},{"img":"picture_live\/2023-05-18\/zsCwGE1111111111111111111111.png","width":260,"height":260,"ratio":"260x260","size":7735}]
     */
    public function batchAdd()
    {
        //数组格式数据
        // $picture_live = [[
        //     "img" => "picture_live/2023-05-17/zsCwGEDXx2OyVuWpJx6EqSCZTwNEkqUyErUtxYYP.png",
        //     "width" => 260,
        //     "height" => 260,
        //     "ratio" => "260x260",
        //     "size" => 7735
        // ], [
        //     "img" => "picture_live/2023-05-18/zsCwGE1111111111111111111111.png",
        //     "width" => 260,
        //     "height" => 260,
        //     "ratio" => "260x260",
        //     "size" => 7735
        // ]];

        //增加验证场景进行验证
        if (!$this->validate->scene('works_batch_add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $pictureLiveModel = new PictureLive();
        $act_info = $pictureLiveModel->detail($this->request->act_id, null, ['con_start_time', 'con_end_time', 'uploads_number', 'uploads_way', 'is_appoint', 'is_check']);
        if (empty($act_info)) {
            return $this->returnApi(201, "活动不存在");
        }
        $act_info = $act_info->toArray();
        //提前一个小时上传
        if ($act_info['con_start_time'] > date('Y-m-d H:i:s', strtotime("+1 hour"))) {
            return $this->returnApi(201, "活动未开始，暂不允许上传");
        }
        //推迟一个小时结束上传
        if ($act_info['con_end_time'] < date('Y-m-d H:i:s', strtotime("-1 hour"))) {
            return $this->returnApi(201, "活动已结束，不允许上传");
        }
        //判断是否可以上传
        if ($act_info['uploads_way'] == 3) {
            return $this->returnApi(201, '此活动，仅支持前台上传，后台不允许上传');
        }

        //计算上传数量
        $pictureLiveWorksModel = new PictureLiveWorks();
        $total_number = $pictureLiveWorksModel->getUserWorksNumber($this->request->act_id);
        $suplus_uploads_number = 500 - $total_number; //总数不能超过500

        $content = json_decode($this->request->content, true);
        if ($suplus_uploads_number - count($content) <= 0) {
            return $this->returnApi(201, '上传张数已达上限,本次最多可上传 ' . $suplus_uploads_number . ' 张'); //已到达上传限制
        }

        $user_id = $this->request->user_id;


        DB::beginTransaction();
        try {
            $status = $act_info['is_check'] == 2 ? 1 : 3;
            $this->model->batchAdd($this->request->act_id, $user_id, $this->request->content, $status);

            /*消息推送*/
            // $system_id = $this->systemAdd('线上大赛投稿作品', $user_id, $account_id, 3, intval($this->model->id), '线上大赛：【' . $contestInfo->title . '】投稿成功，等待后台管理员审核！');

            $msg = $act_info['is_check'] == 2 ? '批量上传成功!' : '批量上传成功，等待后台管理员审核!';

            DB::commit();
            return $this->returnApi(200, $msg, true); //返回用户已投稿数量
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 修改作品上传用户信息
     * @param user_id 用户id  可选
     * @param works_id int 作品id
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('works_change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $works_info = $this->model->where('id', $this->request->works_id)->where('is_del', 1)->first();
        if (empty($works_info)) {
            return $this->returnApi(201, "作品不存在");
        }
        $pictureLiveModel = new PictureLive();
        $act_info = $pictureLiveModel->detail($works_info->act_id, null, ['con_start_time', 'con_end_time', 'uploads_number', 'uploads_way', 'is_appoint', 'is_check']);
        if (empty($act_info)) {
            return $this->returnApi(201, "活动不存在");
        }
        $act_info = $act_info->toArray();
        if ($act_info['con_start_time'] > date('Y-m-d H:i:s', strtotime("+1 hour"))) {
            return $this->returnApi(201, "活动未开始，暂不允许修改");
        }
        if ($act_info['con_end_time'] < date('Y-m-d H:i:s', strtotime("-1 hour"))) {
            return $this->returnApi(201, "活动已结束，不允许修改");
        }
        //判断是否可以修改
        if ($act_info['uploads_way'] == 3) {
            return $this->returnApi(201, '此活动，仅支持前台修改，后台不允许修改');
        }
        $user_id = $this->request->user_id;

        DB::beginTransaction();
        try {
            $this->model->change(['id' => $this->request->works_id, 'user_id' => $user_id]);

            DB::commit();
            return $this->returnApi(200, '修改成功', true); //返回用户已投稿数量
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }



    /**
     * 删除作品
     * @param id int 作品id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('works_del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $id = $this->request->id;
        $works = $this->model->detail($id);
        if (!$works) {
            return $this->returnApi(202, '参数传递错误');
        }
        $res = $this->model->del($id);




        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
    }


    /**
     * 下载直播图片
     * @param act_id int 活动id
     * @param status int 是否审核 状态  1.已通过   2.未通过   3.未审核(默认)   不传为全部
     * @param keywords string 搜索关键词(作品名称|姓名|编号)
     * @param start_time datetime 投稿时间(开始)
     * @param end_time datetime 投稿时间(截止)
     * @param sort 字段排序  1 默认  2 浏览量  3 点赞 
     */
    public function downloadWorksImg()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('production_list_download_img')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $act_id = $this->request->act_id;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $status = $this->request->status;
        $sort = $this->request->input('sort', '1');

        $status = empty($status) ? [1, 2, 3] : [$status];
        $res = $this->model->lists(['img'], $act_id, null, $keywords,  $status, $start_time, $end_time, 2, $sort, 2, 99999);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        $zipFileDownloadObj = new ZipFileDownloadController();
        $path_arr = [];
        foreach ($res['data'] as $key => $val) {
            $path_arr[$key]['file_path'] = $val['img'];
            $path_arr[$key]['file_name'] = $key + 1 . '.png';
        }
        $file_name = PictureLive::where('id', $act_id)->value('title');
        $zip_path = $zipFileDownloadObj->addPackage($path_arr, null, $file_name . '-直播图片下载-' . date('Y-m-d'), 10); //缓存时间长了，筛选数据还是之前的
        //使用大文件下载
        // download_file($zip_path);//前端改为浏览器下载，无总进度
        return response()->download($zip_path); //前端改为浏览器下载，有总进度
    }
}
